package com.somiz.main;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.hibernate.Session;

import com.somiz.structure.Structure;
import com.somiz.utilisateur.Utilisateur;
import com.tech.hibernate.HibernateUtil;

public class main {

	public static void main(String[] args) throws IOException {
		Control control = new Control();
		main main = new main();
		// main.ecrireStructure("c:/temp/strct.xls");
		// main.ecrireUsers("c:/temp/Liste du personnel.xls");
	}

	public void ecrireStructure(String inputFile) throws IOException {
		Session session = HibernateUtil.getSessionFactory().openSession();
		File inputWorkbook = new File(inputFile);
		Workbook w;
		try {
			w = Workbook.getWorkbook(inputWorkbook);
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines
			for (int j = 0; j < sheet.getRows(); j++) {
				Structure structure = new Structure();
				for (int i = 0; i < sheet.getColumns(); i++) {
					Cell cell = sheet.getCell(i, j);
					CellType type = cell.getType();
					if (i == 0)
						structure.setTier(cell.getContents());
					if (i == 1)
						structure.setCode(cell.getContents());
					if (i == 2)
						structure.setDesig(cell.getContents());
				}
				if (structure.getCode() != "")
					Control.getStructureDao().Creer(structure, session);
			}
		} catch (BiffException e) {
			e.printStackTrace();
		}
		session.close();
	}

	public void ecrireUsers(String inputFile) throws IOException {
		Session session = HibernateUtil.getSessionFactory().openSession();
		File inputWorkbook = new File(inputFile);
		Workbook w;
		try {
			w = Workbook.getWorkbook(inputWorkbook);
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines
			for (int j = 0; j < sheet.getRows(); j++) {
				Utilisateur utilisateur = new Utilisateur();
				for (int i = 0; i < sheet.getColumns(); i++) {
					Cell cell = sheet.getCell(i, j);
					CellType type = cell.getType();
					if (i == 0)
						utilisateur.setMatricule(cell.getContents());
					if (i == 2)
						utilisateur.setNomPrenom(cell.getContents());
					if (i == 3)
						utilisateur.setNomPrenom(utilisateur.getNomPrenom()
								+ " " + cell.getContents());
					if (i == 4) {
						Structure structure = new Structure();
						structure.setCode(cell.getContents());
						structure = Control.getStructureDao().TrouverAvecCode(
								structure, session);
						if (structure.getDesig() != null) {
							utilisateur.setStructure(structure);
							Control.getUtilisateurDao().Creer(utilisateur,
									session);
						}
					}
				}

			}
		} catch (BiffException e) {
			e.printStackTrace();
		}
		session.close();
	}
}
